<?php


namespace PKApp\Content\Classes;

use PKApp\Model\Classes\FieldService;
use PKApp\Site\Classes\SiteController;
use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\Auth;
use PKFrame\DataHandler\Numbers;

abstract class ContentDetailController extends SiteController
{

    use TraitContent;

    protected $list_power_field;
    protected $tpl_content;

    protected function getParentIdList()
    {
        $result = [];
        if (!empty($this->getCategoryEntityByNow()->parentIdList)) {
            $parentIdList = explode(',', $this->getCategoryEntityByNow()->parentIdList);
            krsort($parentIdList);
            $categoryListEntity = $this->serviceOfCategory(
                $this->getCategoryEntityByNow()->siteId
            )->GetListById($parentIdList);
            if (Arrays::Is($categoryListEntity)) {
                foreach ($parentIdList as $item_catId) {
                    $tmp = array_filter($categoryListEntity, function ($item_entity) use ($item_catId) {
                        return $item_entity['id'] == $item_catId ? $item_entity : [];
                    });
                    if (Arrays::Is($tmp)) {
                        $tmp = end($tmp);
                        $result[] = [
                            'name' => $tmp['name'],
                            'image' => $tmp['image'],
                            'url' => self::UrlPathOfCategory(
                                $tmp, Arrays::Unserialize($tmp['template']),
                                $this->getSitePath()
                            )
                        ];
                    }
                }
            }
        }
        $this->assign(['categoryParent' => $result]);
    }

    protected function getDetailByPage()
    {
        $service = new PageService();
        $entity = $service->interface_getEntityById($this->getCategoryEntityByNow()->id);
        $params_fieldList = ['title', 'content', 'seoTitle', 'seoKeywords', 'seoDescription'];
        foreach ($params_fieldList as $field) {
            !array_key_exists($field, $entity) ?: $entity[$field] = Auth::HtmlspecialcharsDeCode($entity[$field]);
        }
        $this->assign($entity);
    }

    protected function getModelFieldByPower()
    {
        $service_field = new FieldService();
        $list_field = $service_field->GetListByModelId(
            $this->getCategoryEntityByNow()->modelId,
            ['field', 'power']
        );
        $this->list_power_field = [];
        foreach ($list_field as $item) {
            $power = Arrays::Unserialize(Arrays::GetKey('power', $item));
            if (!empty($power) && $ReadGroup = Arrays::GetKey('ReadGroup', $power)) {
                $this->list_power_field[$item['field']] = explode(',', $item['power']);
            }
        }
    }

    /**
     * 内容服务层
     * @return ContentService
     */
    protected function serviceContent(): ContentService
    {
        static $service;
        if (empty($service)) {
            $service = new ContentService($this->getCategoryEntityByNow()->modelId);
        }
        return $service;
    }

    protected function handlerContentData(array $entity_content = []): array
    {
        if (Arrays::Is($this->list_power_field) && Arrays::Is($entity_content)) {
            foreach ($this->list_power_field as $field => $power) {
                !array_key_exists($field, $entity_content) ?: $entity_content[$field] = language('Content_power_field', 'content');
            }
        }
        $page=null;
        if (request()->has('page', 'get')) {
            $page = Numbers::To(request()->get('page'));
            $entity_content['title'] .= ' (' .$page.')';
            $entity_content['seoTitle'] .= ' (' .$page.')';
        }
        $url_base = self::UrlPathOfContent([
            'id' => $this->getCategoryEntityByNow()->id,
            'modelId' => $this->getCategoryEntityByNow()->modelId,],
            $this->getCategoryEntityByNow()->template,
            $entity_content,
            $this->getSitePath(),
            $page
        );
        if (array_key_exists('pageSize', $entity_content)) {
            $page_nav = ['hone'=>$url_base];
            for ($i = 1; $i<=$entity_content['pageSize']; $i++) {
                $page_nav['size'][$i] = $url_base = self::UrlPathOfContent([
                    'id' => $this->getCategoryEntityByNow()->id,
                    'modelId' => $this->getCategoryEntityByNow()->modelId,],
                    $this->getCategoryEntityByNow()->template,
                    $entity_content,
                    $this->getSitePath(),
                    $i
                );
                if ($i == $entity_content['pageSize']) {
                    $page_nav['end'] = $page_nav['size'][$i];
                } elseif ($i == 1) {
                    $page_nav['hone'] = $page_nav['size'][$i];
                }
                $entity_content['pageNav'] = $page_nav;
            }
        }
        $entity_content = array_merge($entity_content, ['url' => $url_base,]);
        $tplFile = !empty($entity_content['template']) ? $entity_content['template']
            : $this->getCategoryEntityByNow()->template['contentTpl'];
        $this->tpl_content = $this->getTplFileOfCustomize($tplFile);
        return $entity_content;
    }

    //上下篇
    protected function getUpOrNext($contentEntity)
    {
        // 排序方式
        $order_info = Arrays::GetKey(
            Numbers::To($this->getCategoryEntityByNow()->template['orderList']),
            dict('category_content_orderList')
        );
        $order_field = $order_info['field'];
        $order_mode = $order_info['mode'];
        // 条件
        $where = [
            'catId' => $this->getCategoryEntityByNow()->id,
            'siteId' => $this->getCategoryEntityByNow()->siteId,
            'isDeleted' => 0,
        ];
        switch ($order_field) {
            case 'id':
            case 'listSort':
                $order_fieldByMaster = $order_field;
                $order_mode_p = 'DESC';
                $order_mode_n = 'ASC';
                break;
            case 'toTop':
                $order_fieldByMaster = 'id';
                $order_mode_p = 'DESC';
                $order_mode_n = 'ASC';
                break;
        }
        if (isset($order_fieldByMaster) && isset($order_mode_p) && isset($order_mode_n)) {
            // 上一篇
            $previous = $this->serviceContent()->GetContentUpOrNext(array_merge($where, [
                [
                    $order_fieldByMaster,
                    $order_mode == 'DESC' ? '<' : '>',
                    $contentEntity[$order_fieldByMaster]],
            ]), $order_fieldByMaster, $order_mode_p);
            // 下一篇
            $next = $this->serviceContent()->GetContentUpOrNext(array_merge($where, [
                [
                    $order_fieldByMaster,
                    $order_mode == 'DESC' ? '>' : '<',
                    $contentEntity[$order_fieldByMaster]],
            ]), $order_fieldByMaster, $order_mode_n);
        }
        //上下篇的URL规则
        $category = [
            'id' => $this->getCategoryEntityByNow()->id,
            'modelId' => $this->getCategoryEntityByNow()->modelId,
            'title' => $this->getCategoryEntityByNow()->name,
            'url' => $this->getCategoryEntityByNow()->url,
        ];
        $is_previous = isset($previous) && Arrays::Is($previous);
        if ($is_previous) {
            $previous['url'] = self::UrlPathOfContent(
                $category, $this->getCategoryEntityByNow()->template, $previous, $this->getSitePath());
        }
        $is_next = isset($next) && Arrays::Is($next);
        if ($is_next) {
            $next['url'] = self::UrlPathOfContent(
                $category, $this->getCategoryEntityByNow()->template, $next, $this->getSitePath());
        }
        $this->assign([
            'previous' => ($is_previous ? $previous : $category),
            'next' => ($is_next ? $next : $category),
        ]);
    }

}